/*
 * @Descripttion: 
 * @version: 
 * @Author: lily
 * @Date: 2021-05-12 20:43:29
 * @LastEditors: lily
 * @LastEditTime: 2021-05-12 21:18:57
 */
/*
 * @lc app=leetcode.cn id=661 lang=javascript
 *
 * [661] 图片平滑器
 */

// @lc code=start
/**
 * @param {number[][]} img
 * @return {number[][]}
 */

//  思想：
//  找出邻居的个数和总和计算平均值存于新的数组

//  复杂度：O(nm) O(nm)

var imageSmoother = function (img) {
    const row = img.length, col = img[0].length
    let res = Array.from(new Array(row), () => new Array(col).fill(0))
    for (let i = 0; i < row; i++) {
        for (let j = 0; j < col; j++) {
            let count = 0
            // i j差距小于等于1的所有元素 
            // 考虑边缘，取0，或长度-1
            for (let r = Math.max(i - 1, 0); r <= Math.min(i + 1, row - 1); r++) {
                for (let c = Math.max(j - 1, 0); c <= Math.min(j + 1, col - 1); c++) {
                    res[i][j] += img[r][c]
                    count++
                }
            }
            // 计算平均值
            res[i][j] = Math.floor(res[i][j] / count)
        }
    }
    return res
};
// @lc code=end

console.log(imageSmoother([[2, 3, 4], [5, 6, 7], [8, 9, 10], [11, 12, 13], [14, 15, 16]]));